<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
	public function index(){
		//$code = $_GET["code"];
		if (!$weObj =getCache('weObj')) {
			$options = array(
	 		   'token'=>c('wxtoken'), //填写你设定的key
	 		   'encodingaeskey'=>c('encodingaeskey'), //填写加密用的EncodingAESKey
			   'appid'=>c('appid'), //填写高级调用功能的app id, 请在微信开发模式后台查询
	  		   'appsecret'=>c('appsecret') //填写高级调用功能的密钥
	  		   );
		 	$weObj = new \Org\Net\Wechat($options); //创建实例对象
    		setCache('weObj',$weObj);			 					
		};
		$tokenjson=$weObj->getOauthAccessToken();
		$myopenid=$tokenjson['openid'];
		$$access_token=$tokenjson['access_token'];
		$userinfo =$weObj->getOauthUserinfo($$access_token,$myopenid);

		$mysql =new \SaeMysql();
		$sql = "SELECT * FROM `WX_userinfo` WHERE `openid`='".$myopenid."'";
		$row = $mysql->getLine($sql);
		$this->assign('nickname',$userinfo["nickname"]);
		$this->assign('sex',$userinfo["sex"]);
		$this->assign('myopenid',$myopenid);
		if ($row){
			$this->assign('realname',$row["name"]);
			$this->assign('phonenumber',$row["phone"]);		
			$this->assign('address',$row["address"]);					
		} else {
			$this->assign('realname','');
			$this->assign('phonenumber','');		
			$this->assign('address','');			
		    //插入openid到wxuserinfo库中
		    if ($myopenid){
				$sql = "INSERT INTO `WX_userinfo` (`openid`) VALUES ('".$myopenid."')";
				$mysql->runSql($sql);    //执行插入数据的操作		    	
		    }
			if($mysql->errno() != 0 )
			{
				echo "发生错误，请通知管理员";
			}
		}
		$mysql->closeDb();
		$this->display();
	}

	public function update(){
		$name=$_POST["realname"];
		$openid=$_POST["openid"];
		$phone=$_POST["phonenumber"];
		$address=$_POST["address"];

		$mysql =new \SaeMysql();
		$sql = "UPDATE `WX_userinfo` SET `name`='".$name."',`phone`='".$phone."',`address`='".$address."' WHERE `openid`='".$openid."'";
		$mysql->runSql($sql); 
		$mysql->closeDb();		
		if($mysql->errno() != 0 ){
			echo "发生错误1，请通知管理员";
		} else 
		{
			echo "数据已更新！";
		}
	}

}